<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="实付金额" prop="payAmount">
        <el-input
          v-model="queryParams.payAmount"
          placeholder="请输入实付金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="订单编号" prop="orderNumber"> 
         <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入实付金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="确认收货时间" label-width="100px" prop="receiveTime">
        <el-date-picker
          clearable
          v-model="queryParams.receiveTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择确认收货时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
     
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="(item, index) in columns" :key="index">
        <el-table-column
          :label="item.label"
          :align="item.align"
          :prop="item.prop"
          :width="item.width"
          v-if="item.visible"
        >
          <template #default="scope">
            <span
              v-if="
                item.prop === 'payTime' ||
                item.prop === 'shipTime' ||
                item.prop === 'receiveTime'
              "
            >
              {{ parseTime(scope.row[item.prop], "{y}-{m}-{d}") }}
            </span>
            <span v-else-if="item.prop === 'discountType'">
              {{ formatDiscountType(scope.row[item.prop]) }}
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        label="操作"
        fixed="right"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">

          <el-button
            link
            type="primary"
            icon="View"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item
          label="用户ID"
          style="width: 350px"
          label-width="100px"
          prop="userId"
        >
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item
          label="收货地址ID"
          style="width: 350px"
          label-width="100px"
          prop="addressId"
        >
          <el-input v-model="form.addressId" placeholder="请输入收货地址ID" />
        </el-form-item>
        <el-form-item
          label="订单总金额"
          style="width: 350px"
          label-width="100px"
          prop="totalAmount"
        >
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" />
        </el-form-item>
        <el-form-item
          label="实付金额"
          style="width: 350px"
          label-width="100px"
          prop="payAmount"
        >
          <el-input v-model="form.payAmount" placeholder="请输入实付金额" />
        </el-form-item>
        <el-form-item
          label="运费"
          style="width: 350px"
          label-width="100px"
          prop="freight"
        >
          <el-input v-model="form.freight" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="支付时间" label-width="100px" prop="payTime">
          <el-date-picker
            clearable
            v-model="form.payTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label-width="100px" label="发货时间" prop="shipTime">
          <el-date-picker
            clearable
            v-model="form.shipTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label-width="100px"
          label="确认收货时间"
          prop="receiveTime"
        >
          <el-date-picker
            clearable
            v-model="form.receiveTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择确认收货时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="openDetail" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ detailData.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailData.userId }}</el-descriptions-item>
        <el-descriptions-item label="订单总金额">{{ detailData.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="实付金额">{{ detailData.payAmount }}</el-descriptions-item>
        <el-descriptions-item label="运费">{{ detailData.freight }}</el-descriptions-item>
        <el-descriptions-item label="折扣类型">{{ formatDiscountType(detailData.discountType) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ detailData.status }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ parseTime(detailData.payTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ parseTime(detailData.shipTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="确认收货时间">{{ parseTime(detailData.receiveTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ detailData.receiver }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.phone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ detailData.country }} {{ detailData.state }} {{ detailData.city }} {{ detailData.street }} {{ detailData.detail }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">订单项</el-divider>
      
      <el-table :data="detailData.orderItems" border style="width: 100%">
        <el-table-column prop="imgUrl" label="商品图片" width="100">
          <template #default="scope">
            <el-image
              :src="scope.row.imgUrl"
              fit="cover"
              style="width: 60px; height: 60px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="skuName" label="商品名称"></el-table-column>
        <el-table-column prop="skuCode" label="商品编码" width="180"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="100"></el-table-column>
        <el-table-column prop="totalPrice" label="小计" width="100">
          <template #default="scope">
            {{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openDetail = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import {
  listOrder,
  getOrderDetail
} from "@/api/order/order";

const { proxy } = getCurrentInstance();

const orderList = ref([]);
const open = ref(false);
const openDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 列显隐数据
const columns = ref([
  { key: 0, label: `订单号`, prop: `orderNumber`, width:`200`, align: `center`, visible: true },
  // { key: 1, label: `用户名称`, prop: `userId`, align: `center`, visible: true },
  {
    key: 2,
    label: `订单总金额`,
    prop: `totalAmount`,
    align: `center`,
    visible: true,
  },
  {
    key: 3,
    label: `折扣类型`,
    prop: `discountType`,
    align: `center`,
    visible: true,
  },
  {
    key: 4,
    label: `实付金额`,
    prop: `payAmount`,
    align: `center`,
    visible: true,
  },
  { key: 5, label: `运费`, prop: `freight`, align: `center`, visible: true },
  { key: 6, label: `订单状态`, prop: `status`, align: `center`, visible: true },
  {
    key: 7,
    label: `支付时间`,
    prop: `payTime`,
    align: `center`,
    width: `180`,
    visible: true,
  },
  {
    key: 8,
    label: `发货时间`,
    prop: `shipTime`,
    align: `center`,
    width: `180`,
    visible: true,
  },
  {
    key: 9,
    label: `确认收货时间`,
    prop: `receiveTime`,
    align: `center`,
    width: `180`,
    visible: true,
  },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    addressId: null,
    totalAmount: null,
    orderNumber:null,
    discountType: null,
    payAmount: null,
    freight: null,
    status: null,
    payTime: null,
    shipTime: null,
    receiveTime: null,
  },
  rules: {},
  detailData: {}
});

const { queryParams, form, rules, detailData } = toRefs(data);

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then((response) => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error('获取订单列表失败:', error);
    loading.value = false;
    proxy.$modal.notifyError('获取订单列表失败');
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    userId: null,
    addressId: null,
    totalAmount: null,
    discountType: null,
    payAmount: null,
    freight: null,
    status: null,
    payTime: null,
    shipTime: null,
    receiveTime: null,
    createTime: null,
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单";
}

/** 修改按钮操作 */
// function handleUpdate(row) {
//   reset();
//   const _orderId = row.orderId || ids.value;
//   getOrder(_orderId).then((response) => {
//     form.value = response.data;
//     open.value = true;
//     title.value = "修改订单";
//   });
// }

/** 提交按钮 */
// function submitForm() {
//   proxy.$refs["orderRef"].validate((valid) => {
//     if (valid) {
//       if (form.value.orderId != null) {
//         updateOrder(form.value).then((response) => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         }).catch(error => {
//           console.error('修改订单失败:', error);
//           proxy.$modal.notifyError('修改订单失败');
//         });
//       } else {
//         addOrder(form.value).then((response) => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         }).catch(error => {
//           console.error('新增订单失败:', error);
//           proxy.$modal.notifyError('新增订单失败');
//         });
//       }
//     }
//   });
// }

/** 删除按钮操作 */
// function handleDelete(row) {
//   const _orderIds = row.orderId || ids.value;
//   proxy.$modal
//     .confirm('是否确认删除订单编号为"' + _orderIds + '"的数据项？')
//     .then(function () {
//       return delOrder(_orderIds);
//     })
//     .then(() => {
//       getList();
//       proxy.$modal.msgSuccess("删除成功");
//     })
//     .catch(() => {});
// }

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download(
//     "order/order/export",
//     {
//       ...queryParams.value,
//     },
//     `order_${new Date().getTime()}.xlsx`
//   );
// }

/** 订单详情 */
function handleDetail(row) {
  getOrderDetail(row.orderId).then(response => {
    data.detailData = response.data;
    openDetail.value = true;
  }).catch(error => {
    console.error('获取订单详情失败:', error);
    proxy.$modal.notifyError('获取订单详情失败');
  });
}

/** 格式化折扣类型 */
function formatDiscountType(type) {
  const discountTypes = {
    0: '无折扣',
    1: '优惠券',
    2: '积分抵扣',
    3: '满减'
  };
  return discountTypes[type] || '未知类型';
}

getList();
</script>